package com.hcx.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hcx.reggie.pojo.User;
import com.hcx.reggie.service.UserService;
import com.hcx.reggie.utils.R;
import com.hcx.reggie.utils.SMSUtils;
import com.hcx.reggie.utils.ValidateCodeUtils;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

@Slf4j
@Controller
@ResponseBody
@RequestMapping("user")
public class UserController{
    @Autowired
    private UserService userService;

    /**
     * 发送手机验证码
     * @param user
     * @return
     */
    @PostMapping("sendMsg")
    public R<String> sendMsg(@RequestBody User user,HttpSession session){
        //获取手机号
        String phone = user.getPhone();
        if (phone != null){
            //生成一个四位的验证码
            Integer code = ValidateCodeUtils.generateValidateCode(4);
            log.info("{}",code);
            //发送手机验证码
//            SMSUtils.sendMessage("瑞吉外卖","",phone,code );
            //保存验证码Session
            session.setAttribute(phone,code.toString());
            return R.success("验证码发送成功！");
        }
        return R.error("验证码发送失败！");
    }
    @PostMapping("login")
    public R<User> login(@RequestBody Map map,HttpSession session){
        log.info(map.toString());
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();
        Object codeInSession = session.getAttribute(phone);
        if (codeInSession != null && codeInSession.equals(code)){
            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.eq(User::getPhone,phone);
            User serviceOne = userService.getOne(userLambdaQueryWrapper);
            if (serviceOne == null){
                serviceOne = new User();
                serviceOne.setPhone(phone);
                serviceOne.setStatus(1);
                userService.save(serviceOne);
            }
            session.setAttribute("user",serviceOne.getId());
            return R.success(serviceOne);
        }
        return R.error("短信登录失败");
    }
 }
